import {makeAutoObservable} from "mobx";
import {OffsetDateTime} from "@js-joda/core";
import Taro from "@tarojs/taro";
import {GoodsUnitResponse} from "../apis/GoodsApi";

export const ScratchDocumentStorageKeyPrefix = "ScratchDocument-"

class ScratchDocumentStore {
    documents: ScratchDocumentData[] = []

    get sortedDocuments() {
        return this.documents.length >= 2 ? this.documents.slice().sort((a, b) => {
            return OffsetDateTime.parse(b.createdDateTime).compareTo(OffsetDateTime.parse(a.createdDateTime));
        }) : this.documents
    }

    constructor() {
        makeAutoObservable(this)
    }

    async create() {
        const date = OffsetDateTime.now().toString()
        let newData = {
            createdDateTime: date,
            useAmount: false,
            useNote: false,
            items: []
        };
        await Taro.setStorage({
            key: ScratchDocumentStorageKeyPrefix + date.toString(),
            data: newData
        },)
        this.documents.push(newData)
        this.documents = Array.from(this.documents)
    }

    async getAll(): Promise<ScratchDocumentData[]> {
        return new Promise((resolve, reject) => {
            Taro.getStorageInfo({
                success: (result) => {
                    let myKeys = result.keys.filter(it => it.startsWith(ScratchDocumentStorageKeyPrefix)) ?? [];
                    if (myKeys.length) {
                        let data = Taro.batchGetStorageSync<ScratchDocumentData>(myKeys) ?? [];
                        this.documents = data
                        resolve(data)
                    } else {
                        resolve([])
                    }
                },
                fail: (e) => {
                    console.error(e)
                    reject(e)
                }
            })
        })
    }

    async delete(createdDateTime: string) {
        return await Taro.removeStorage({
            key: createdDateTime
        }).then(() => {
            this.documents = this.documents.filter(it => it.createdDateTime !== createdDateTime)
        })
    }

    async set(data: ScratchDocumentData) {
        await Taro.setStorage({key: ScratchDocumentStorageKeyPrefix + data.createdDateTime, data})
        let index = this.documents.findIndex(it => it.createdDateTime === data.createdDateTime);
        let item = this.documents[index]
        if (item) {
            this.documents[index] = ({
                ...item,
                ...data,
                createdDateTime: item.createdDateTime
            })
        }

        this.documents = Array.from(this.documents)
    }

}

export interface ScratchDocumentData {
    createdDateTime: string
    useNote: boolean
    useAmount: boolean
    items: ScratchDocumentItem[]
}

export interface ScratchDocumentItem {
    id: number
    name: string
    price: number
    amount?: number
    barcode: string
    note?: string
    unit?: {
        id: number
        name: string
    }
    units: GoodsUnitResponse[]
    subGoods?: {
        id: number
        number: string
        name: string
    }
}

export default new ScratchDocumentStore()